<?php
Import::appLibs("Configuration");
class CandidateController extends Controller {
	private $can_session ;
	private $emp_session ;
	/* Mr. Chamroeun Oum
	 * Function to retrive all employers to build up employers table for ajax call
	*/
	public function __construct(){
		$this->calledClass(get_class($this));
		$this->can_session = Session::get("candidate");
		$this->emp_session = Session::get("employer");
		$this->profilepicture();
	}
	public function profilepicture(){
		$resume = $this->loadModel("Resume");
		$row = $resume->getResumeWithUser($this->can_session["id"]) ;
		$profilePhoto = !empty($row )&&is_object($row->rem_uploadImg)?ROOT.$row->rem_uploadImg->location:"";
		$this->set(array("profile_picture"=>$profilePhoto));
	}
	public function candidates(){
		$candidates= $this->loadModel("Candidate");
		//$records = $employer->getList($page=1,$perpage=20,$search="",$searchFields=array(),$sortFields=array(),$sortCriteria="");
		$page = $this->get("page")!=NULL?$this->get("page"):1;
		$perpage = $this->get("perpage")!=NULL?$this->get("perpage"):20;
		$search = $this->get("search")!=NULL?$this->get("search"):"";
		$records = $candidates->getList($page,$perpage,$search,array("firstname","lastname","username","email"),array());
		$this->set(array("records"=>$records));
		$this->render("admin_display");
	}
	public function job(){
		$candidates= $this->loadModel("Job");
		$this->showItemsDropdownSearch();
		$this->set(array("Getcategory"=>$candidates->SelectC()));
		//$records = $employer->getList($page=1,$perpage=20,$search="",$searchFields=array(),$sortFields=array(),$sortCriteria="");
		$this->set(array("records"=>$candidates->getJobPublish($this->get("page"),20,$this->get("search"),array("firstname","lastname","username","email"),array())));
		$this->render("display");
	}
	public function share(){
		$facebook = $this->loadModel("Facebook");
		$candidates= $this->loadModel("Job");
		$idsharejob=$this->get("idsharejob");
		//$this->set(array("arrFind"=>$jobs->findObject(array("id="=>$this->get("pid")))));
		$this->set(array("share"=>array("data-href"=>'http://www.hrcambodia.com',
				"data-type"=>"button_count")));
		$this->render("share");
	}
	public function applyPage(){
		$this->set(array("layout"=>"applyjob"));
		$candidate=$this->loadModel("Candidate");
		$apply=$this->loadModel("NotiApplie");
		$resume=$this->loadModel("Resume");
		$cv_can_gal=$resume->viewCV($this->can_session["id"]);
		if($cv_can_gal=="" && $cv_can_gal==null){
			echo 1;
		}else{
			/* start save apply job  */
			$postid=@$apply->getCompApplyID($this->get("id"),$this->can_session["id"]);
			$canid=$apply->getCandidatid($this->can_session["id"]);
			if($postid==$this->get("id") && $canid==$this->can_session["id"]){
				echo 2;
			}
			else{
			/* end save apply job  */
			$username=$cv_can_gal->firstname." ".$cv_can_gal->lastname;
			$email= $cv_can_gal->email;
			$cvpath=$cv_can_gal->location;
			$emp_job=$candidate->getRecordSendMail($this->get("id"));
			$candidate_email = $candidate->getCanEmail($this->can_session["id"]);
			$employer_email=$emp_job->email ;
			/* $photo=$this->upload(); */
			$str = "<b>HRCambodia .com Alert Apply Job Information</b><br/>";
			$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>Name : </span><span style='font-family: Trebuchet MS;padding-right:5px;font-weight:bold'>" . $username ."</span><br/>";
			$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>Email : </span><span style='font-family: Trebuchet MS;padding-right:5px;font-weight:bold'>" . $email ."</span><br/>";
			$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>Apply Date : </span><span style='font-family: Trebuchet MS;padding-right:5px;font-weight:bold'>" . date("d-m-Y ") ."</span><br/>";
			$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>Title : </span><span style='font-family: Trebuchet MS;padding-right:5px;font-weight:bold'>" . $emp_job->title ."</span><br/>";
			$str .="<span style='font-family: Trebuchet MS;padding-right:5px'>Post Date : </span><span style='font-family: Trebuchet MS;padding-right:5px;font-weight:bold'>" . $emp_job->start_date ."</span><br/>";
			//$str .="<span style='font-family: Trebuchet MS;padding-right:5px'><a href='".SERVER.ROOT."'>Click here to view detail information.</a></span>";
			//send mail to employer after updated status
			ob_start();
			//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
			Import::util('class.phpmailer');
			//the true param means it will throw exceptions on errors, which we need to catch
			$mail = new PHPMailer(true);
			//telling the class to use SMTP
			$mail->IsSMTP();
			try {
				// SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
				$mail->SMTPDebug = 1;
				// enable SMTP authentication
				$mail->SMTPAuth = true;
				// sets the SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// set the SMTP port for the MY OWN DOMAIN server
				$mail->Port = 26;
				// SMTP account username
				$mail->Username = "demo@atmos-techno.com";
				// SMTP account password
				$mail->Password = "demo*123456";
				//$mail->AddAddress('physopheak10@gmail.com', '');
				$email_address = filter_input(INPUT_GET,$email, FILTER_VALIDATE_EMAIL);
				if (!$email_address) {
					$apply->save(array("job_id"=>$this->get("id"),"can_id"=>$this->can_session["id"],"date_apply"=>date("y-m-d h:m:s")));
					$mail->SetFrom($email, 'HRCambodia');
					// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
					$mail->AddAddress($employer_email,$employer_email);
					$mail->AddAddress($candidate_email,$candidate_email);
					//$mail->AddAddress('physopheak10@gmail.com','');
					$mail->AddReplyTo($employer_email, $employer_email);
					$mail->Subject ='Job Applied, posted your ads from HRCambodia .com as '.$emp_job->title;
					// optional - MsgHTML will create an alternate automatically
					$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
					$mail->MsgHTML($str);
					$mail->Send();
				} else {
					//echo 'Email is invalid...';
					break;
				}
			} catch (phpmailerException $e) {
				//Pretty error messages from PHPMailer
				echo $e->errorMessage();
			} catch (Exception $e) {
				//Boring error messages from anything else!
				echo $e->getMessage();
			}

		 }
		}
		//$this->render("apply");
	}
	
	/*   start save job  */
	public function savejob(){
		$job= $this->loadModel("Job");
		$savejob= $this->loadModel("SaveJob");
		$postid=@$savejob->getCompSavePostID($this->get("id"),$this->can_session["id"]);
		$canid=$savejob->getCandidatid($this->can_session["id"]);
		if($postid==$this->get("id") && $canid==$this->can_session["id"]){
			echo 2;
		}else{
			$savejob->saveJobs(array("post_id"=>trim($this->get("id")),"save_date"=>date("y-m-d h:m:s"),"user_id"=>$this->can_session["id"]));
			echo 1;
		}
			
	}
	/*   end save job  */
	/*   start Unsave job  */
	public function unsavejob(){
		$job= $this->loadModel("Job");
		$savejob= $this->loadModel("SaveJob");
		$recordSaveJob = $savejob->findAsObject(array("post_id = "=>$this->get("id")));
		if($recordSaveJob){
			$savejob->delete(array("post_id ="=>$recordSaveJob->post_id));
		}else{
			echo 1;
		}
	}
	/*   end unsave job  */
	public function selectFavoriteJob(){
		//print_r($this->get("page"));
		$savejob = $this->loadModel("SaveJob");
		$categories=$this->loadModel("Categorie");
		$membership = $this->loadModel("Membership");
		$savejob = $this->loadModel("SaveJob");
		$apply = $this->loadModel("NotiApplie");
		$this->set(array("jobcategory"=>$categories->getCategories(23)));
		$this->set(array("location"=>$categories->getCategories(1)));
		$this->set(array("jobType"=>$categories->getCategories(20)));
		$records = $savejob->getSaveJobs($this->get("page"),12,$this->can_session["id"]);
		$checkMembership = array();
		foreach ($records["records"] as $rocord){
			$checkMembership[] = $membership->findObject(array("user_id ="=>$this->can_session["id"],"cat_id="=>$rocord->job_category));
		}
		$checkSaveJob = array();
		foreach ($records["records"] as $rocord){
			$checkSaveJob[] = $savejob->findObject(array("user_id ="=>$this->can_session["id"],"post_id="=>$rocord->id));
		}
		$checkApply = array();
		foreach ($records["records"] as $rocord){
			$checkApply[] = $apply->findObject(array("can_id ="=>$this->can_session["id"],"job_id="=>$rocord->id));
		}
		$this->set(array("list"=>$records));
		$this->set(array("checkSaveJobs"=>$checkSaveJob));
		$this->set(array("checkApplys"=>$checkApply));
		$this->set(array("memberships"=>$checkMembership));
		$this->set(array("layout"=>"favoritejob"));
		$this->render("admin");
	}
	public function searchFavoriteJob(){
		$savejob = $this->loadModel("SaveJob");
		$categories=$this->loadModel("Categorie");
		$membership = $this->loadModel("Membership");
		$savejob = $this->loadModel("SaveJob");
		$apply = $this->loadModel("NotiApplie");
		$this->set(array("jobcategory"=>$categories->getCategories(23)));
		$this->set(array("location"=>$categories->getCategories(1)));
		$this->set(array("jobType"=>$categories->getCategories(20)));
		$records = $savejob->getSaveJobs($this->get("page"),12,$this->can_session["id"]);
		$checkMembership = array();
		foreach ($records["records"] as $rocord){
			$checkMembership[] = $membership->findObject(array("user_id ="=>$this->can_session["id"],"cat_id="=>$rocord->job_category));
		}
		$checkSaveJob = array();
		foreach ($records["records"] as $rocord){
			$checkSaveJob[] = $savejob->findObject(array("user_id ="=>$this->can_session["id"],"post_id="=>$rocord->id));
		}
		$checkApply = array();
		foreach ($records["records"] as $rocord){
			$checkApply[] = $apply->findObject(array("can_id ="=>$this->can_session["id"],"job_id="=>$rocord->id));
		}
		$this->set(array("list"=>$records));
		$this->set(array("checkSaveJobs"=>$checkSaveJob));
		$this->set(array("checkApplys"=>$checkApply));
		$this->set(array("memberships"=>$checkMembership));
		$this->render("pagination_favorite_job");
	}
	public function UnfavoriteJob(){
		$savejob = $this->loadModel("SaveJob");
		$savejob->delete(array("post_id="=>$this->get("id")));
		echo 1;
	}

	public function searchJob(){
		$candidates = $this->loadModel("Job");
		$category=$this->get("category");
		$location=$this->get("location");
		$jobtime=$this->get("jobtime");
		$description=$this->get("description");
		$this->set(array("categorys"=>$category));
		$this->set(array("locations"=>$location));
		$this->set(array("jobtimes"=>$jobtime));
		$this->set(array("descriptions"=>$description));
		
		if($category || $location || $jobtime || $description ){
			$this->set(array("records"=>$candidates->getAdvanceSearchJobAll($this->get("page"),20,array("job_category"=>$category,"location"=>$location,"title"=>$description,"job_time"=>$jobtime),array("created"),"DESC","AND")));
		}else {
			$this->set(array("records"=>$candidates->getAdvanceSearchJobAll($this->get("page"),20,array("job_category"=>$category,"location"=>$location,"title"=>$description,"job_time"=>$jobtime),array("created"),"DESC")));

		}
		$this->showItemsDropdownSearch();
		//$this->set(array("list"=>$jobs->getList($this->get("page"),12,$this->get("search"),array("id","title","by_company","job_category","location","expire_date"),array("created"),"DESC")));
		$this->render("display");
	}
	public function adminPage(){
		$gallery = $this->loadModel("Gallery");
		$resume = $this->loadModel("Resume");
		$saveJob = $this->loadModel("SaveJob");
		$appyJob = $this->loadModel("NotiApplie");
		$membership = $this->loadModel("Membership");
		$category = $this->loadModel("Categorie");
		$row = $resume->getResumeWithUser($this->can_session["id"]) ;
		
		$profilePhoto = !empty($row )&&is_object($row->rem_uploadImg)?ROOT.$row->rem_uploadImg->location:"";
		$this->set(array("profile_picture"=>$profilePhoto));
			
		$this->set(array("saveJob"=>$saveJob->getPage($this->can_session["id"],1,20,array(),"DESC")));
		$this->set(array("appyJob"=>$appyJob->getPage($this->can_session["id"],1,20,array("date_apply"),"DESC")));
		$this->set(array("memCat"=>$membership->getPage($this->can_session["id"],1,20,array("created"),"DESC")));
		$this->set(array("memLoc"=>$membership->getPage1($this->can_session["id"],1,20,array("created"),"DESC")));
		$this->set(array("memType"=>$membership->getPage2($this->can_session["id"],1,20,array("created"),"DESC")));

		$categories = $category->getCategoriesAsArray();
		$this->set(array("jobcategory"=>$category->getCategories(23)));
		$this->set(array("jobloc"=>$category->getCategories(1)));
		$this->set(array("jobtime"=>$category->getCategories(20)));
		$this->set(array("categories"=>$categories));

		//scoring of candidate
		$point = $this->loadModel("Point");
		$point_record = $point->findAsObject(array("can_id="=>$this->can_session["id"]));
		$this->set(array("candidate_point"=>($point_record->resume + $point_record->introduce)));
			
		$this->render("admin");
	}
	
	public function adminAccount(){
		$candidate = $this->loadModel("Candidate");
		$this->profilepicture();
		$this->set(array("record"=>$candidate->findAsObject(array("id="=>$this->can_session["id"]))));
		$this->set(array("layout"=>"account"));
		$this->render("admin");
	}
	public function adminResume(){
		$candidat = $this->loadModel("Candidate");
		$this->set(array("rows"=>$candidat->getcandidate(array("id="=>$cid))));
		$this->set(array("layout"=>"resume"));
		$this->render("admin");
	}
	public function adminJob(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$membership = $this->loadModel("Membership");
		$savejob = $this->loadModel("SaveJob");
		$apply = $this->loadModel("NotiApplie");

		$resume = $this->loadModel("Resume");
		$row = $resume->getResumeWithUser($this->can_session["id"]) ;
		$profilePhoto = !empty($row )&&is_object($row->rem_uploadImg)?ROOT.$row->rem_uploadImg->location:"";
		$this->set(array("profile_picture"=>$profilePhoto));
		
		//=$apply->getJobApplied();
		$applyr=$apply->getJobApplied();
		$this->set(array("applied"=>$applyr,"c_id"=>$this->can_session["id"]));
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		$records = $post->displayJobApp($this->get("page"),4,array("title"=>$this->get("s"),"job_category"=>$this->get("c"),"location_category"=>$this->get("l"),"job_type"=>$this->get("t")),array("post_mode"),"DESC","AND");
		$checkMembership = array();
		$c=urldecode($this->get("c"));
		if($this->get("c")){
			$c=str_replace("%2F","/",$c);
			$c=str_replace("%20"," ",$c);
		}
		foreach ($records["records"] as $rocord){
			$checkMembership[] = $membership->findObject(array("user_id ="=>$this->can_session["id"],"cat_id="=>$rocord->job_category));
		}
		$checkSaveJob = array();
		foreach ($records["records"] as $rocord){
			$checkSaveJob[] = $savejob->findObject(array("user_id ="=>$this->can_session["id"],"post_id="=>$rocord->id));
		}
		$checkApply = array();
		foreach ($records["records"] as $rocord){
			$checkApply[] = $apply->findObject(array("can_id ="=>$this->can_session["id"],"job_id="=>$rocord->id));
		}
		$this->set(array("checkSaveJobs"=>$checkSaveJob));
		$this->set(array("checkApplys"=>$checkApply));
		$this->set(array("memberships"=>$checkMembership));
		$this->profilepicture();
		$job = $this->loadModel("Job");
		$this->set(array("categories"=>$job->getJobCategories()));
		$this->set(array("locations"=>$job->getJobLocations()));
		$this->set(array("types"=>$job->getJobTypes()));
		$savejob = $this->loadModel("SaveJob");
		$this->set(array("savejobs"=>$savejob->getAllSavedJobs(),"can_id"=>$this->can_session["id"]));
		$post = $this->loadModel("Post");
		$records = $post->displayJobApp($this->get("p"),20,array("title"=>urldecode($this->get("s")),"job_category"=>$c,"location_category"=>urldecode($this->get("l")),"job_type"=>urldecode($this->get("t"))),array("post_mode"),"DESC","AND");
		$this->set(array("list"=>$records));
		//exit();
		$this->set(array("c"=>$c,"l"=>urldecode($this->get("l")),"t"=>urldecode($this->get("t")),"s"=>urldecode($this->get("s"))));
		$this->set(array("layout"=>"job"));
		$this->render("admin");
	}
	public function admindetail(){
		if($this->get("id")!=NULL){
			$candidate = $this->loadModel("Candidate");
			$resume = $this->loadModel("Resume");
			$this->set("can_id",$this->get("id") );
			//$resume = $resume->getList($this->get("id"),1,4,"",array("id"),array("id"),"DESC");
			//$this->set(array("resumes"=>$resumes));
			$candidate->update(array("admin_view"=>1),array("id="=>$this->get("id")));
			$this->set(array("candidate"=>$candidate->findAsObject(array("id="=>$this->get("id")))));
			$this->render("admin_detail");
		}else{
			echo "Please specify id of employer";
		}
	}
	public function superadminaccount(){		
		$candidate = $this->loadModel("Candidate");
		$this->set(array("candidate"=>$candidate->findAsObject(array("id="=>$this->get("id") )) ) );
		$this->render("admin_account");
	}
	public function adminjobs(){
		$candidate = $this->loadModel("Candidate");
		$savejob = $this->loadModel("SaveJob");
		if($this->get("id")!=NULL){
			$this->set(array("records"=>$savejob->getFavorite($this->get("id"),1,20) ) );
			$this->render("admin_jobs");
		}else{
			echo "Employer id is not specified.";
		}
	}

	public function adminapplys(){
		$candidate = $this->loadModel("Candidate");
		$apply=$this->loadModel("NotiApplie");
		if($this->get("id")!=NULL){
			$this->set(array("records"=>$apply->getApply($this->get("id"),1,20) ) );
			$this->render("admin_applys");
		}else{
			echo "Employer id is not specified.";
		}
	}
	public function adminResumeview(){
		$resume = $this->LoadModel("Resume");
		$gallery= $this->loadModel("Gallery");
		$category = $this->loadModel("Categorie");
		$row = $resume->getResumeWithUser($this->get("id"),$this->can_session["id"]) ;
		$profilePhoto = !empty($row )&&is_object($row->rem_uploadImg)?ROOT.$row->rem_uploadImg->location:"";
		$this->set(array("profile_picture"=>$profilePhoto));
		$this->set(array("row"=>$row));
		$this->set(array("exp_years"=>$category->SelectQu(133)));
		$this->set(array("edu_degrees"=>$category->SelectQu(138)));
		$this->set(array("locations"=>$category->SelectQu(1)));
		$this->set(array("positions"=>$category->SelectQu(150)));
		$this->set(array("postcodes"=>$category->SelectQu(180)));
		$this->set(array("nationalities"=>$category->SelectQu(34)));
		$this->set(array("categories"=>$category->SelectQu(23)));
		$this->set(array("code"=>$resume->SelectQu(180)));
		$this->set(array("gender"=>$resume->SelectQu(219)));
		$this->set(array("layout"=>"resume")); 
		$this->render("admin_resume");
		
	}

	public function searchjobajax(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$membership = $this->loadModel("Membership");
		$savejob = $this->loadModel("SaveJob");
		$apply = $this->loadModel("NotiApplie");
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		$records = $post->displayJobApp($this->get("page")+1,4,array("title"=>$this->get("s"),"job_category"=>$this->get("c"),"location_category"=>$this->get("l"),"job_type"=>$this->get("t")),array("post_mode"),"DESC","AND");
		$checkMembership = array();
		foreach ($records["records"] as $rocord){
			$checkMembership[] = $membership->findObject(array("user_id ="=>$this->can_session["id"],"cat_id="=>$rocord->job_category));
		}
		$checkSaveJob = array();
		foreach ($records["records"] as $rocord){
			$checkSaveJob[] = $savejob->findObject(array("user_id ="=>$this->can_session["id"],"post_id="=>$rocord->id));
		}
		$checkApply = array();
		foreach ($records["records"] as $rocord){
			$checkApply[] = $apply->findObject(array("can_id ="=>$this->can_session["id"],"job_id="=>$rocord->id));
		}
		$this->set(array("list"=>$records));
		$this->set(array("checkSaveJobs"=>$checkSaveJob));
		$this->set(array("checkApplys"=>$checkApply));
		$this->set(array("memberships"=>$checkMembership));
		$this->set(array("cate"=>$this->get("c"),"loc"=>$this->get("l"),"jt"=>$this->get("t"),"search"=>$this->get("s")));
			
		$this->render("searchjobajax");
			
	}
	public function searchFavorite(){
		$post = $this->loadModel("Post");
		$category=$this->loadModel("Categorie");
		$membership = $this->loadModel("Membership");
		$savejob = $this->loadModel("SaveJob");
		$apply = $this->loadModel("NotiApplie");
		$this->set(array("location"=>$category->GetJobTime(1)));
		$this->set(array("jobcategory"=>$category->GetJobTime(23)));
		$this->set(array("jobType"=>$category->GetJobTime(20)));
		$records = $post->displayJobApp($this->get("page"),20,array("title"=>$this->get("s"),"job_category"=>$this->get("c"),"location_category"=>$this->get("l"),"job_type"=>$this->get("t")),array("post_mode"),"DESC","AND");
		$checkMembership = array();
		foreach ($records["records"] as $rocord){
			$checkMembership[] = $membership->findObject(array("user_id ="=>$this->can_session["id"],"cat_id="=>$rocord->job_category));
		}
		$checkSaveJob = array();
		foreach ($records["records"] as $rocord){
			$checkSaveJob[] = $savejob->findObject(array("user_id ="=>$this->can_session["id"],"post_id="=>$rocord->id));
		}
		$checkApply = array();
		foreach ($records["records"] as $rocord){
			$checkApply[] = $apply->findObject(array("can_id ="=>$this->can_session["id"],"job_id="=>$rocord->id));
		}
		$this->set(array("list"=>$records));
		$this->set(array("checkSaveJobs"=>$checkSaveJob));
		$this->set(array("checkApplys"=>$checkApply));
		$this->set(array("memberships"=>$checkMembership));
		$this->set(array("cate"=>$this->get("c"),"loc"=>$this->get("l"),"jt"=>$this->get("t"),"search"=>$this->get("s")));
		$this->render("searchjobajax");
	}
	
	public function registerPage(){
		$this->render("register");
	}
	public function resetPage(){
		@$recordCan = @$this->model->findAsObject(array("id="=>$this->get("canId")));
		if(@$recordCan->link_expire > date("Y-m-d H:i:s")){
			$this->set("recordCan",@$recordCan);
			$this->render("reset");
		}else{
			$this->render("link_expire");
		}
	}
	public function newPasswordForgot(){
		$employer = $this->loadModel("Candidate");
		if($this->get("newpwd")==$this->get("confirmpwd")){
			$row = $employer->update(array("password"=>md5($this->get("newpwd"))
			),array("id="=>$this->get("canId")));
			echo 1;
		}
	}
	public function loginPage(){
		$this->set(array("title"=>"Candidate Login | HR Cambodia - The best website to find job","active_menu"=>"canloginpage" ));
		$this->render("login");
	}
	public function accountPage(){
		$candidate = $this->loadModel("Candidate");
		$this->set(array("record"=>$candidate->findAsObject(array("id="=>$this->can_session["id"]))));
		$this->render("account");
	}
	public function login(){
		$user = $this->loadModel("User");
		$job_seeker = $this->loadModel("Candidate");
		$config = $this->loadModel("Config");
		$config = $config->findAsObject(array("id="=>1));
		$result = $user->checkRecord("Candidates",array("username","password"),array("username="=>$this->get("username"),"password="=>md5($this->get("password"))));
		if($result){
			//$sessionId = $user->getFieldValue("Sessions",array("sessionid"),array("userid="=>$this->get("username")," ip="=>$_SERVER['REMOTE_ADDR'],"ORDER BY "=>"logged" , "LIMIT 0,1 "=>"" ));
			$sessionId = $user->getSessionId($this->get("username"),$_SERVER['REMOTE_ADDR']);
			if(!Session::exist("candidate")){
				$id=$user->getFieldValue("Candidates",array("id"),array("username="=>$this->get("username"),"password="=>md5($this->get("password"))));
				Session::set("candidate" ,array(
					"id"=>is_array($id)&&!empty($id)?$id[0]->id:0,
					"session"=> $sessionId ,
					"user" => $this->get("username")
				));
				$candidate=Session::get("candidate");
				$user->saveUserSession(array(
						"sessionid"=>md5(time().$candidate["user"].$_SERVER["REMOTE_ADDR"]),
						"version"=>1,
						"logged"=>date("Y-m-d H:i:s"),
						"ip"=>$_SERVER["REMOTE_ADDR"],
						"userid"=>$candidate["user"],
						"type"=>Configuration::getNodeValue("Candidate_Type"),
						"duration"=>$config->duration."mn"
				));
				$login_count = $job_seeker->findAsObject(array("id="=>$candidate['id']));
				$job_seeker->update(array("login_date"=>date("Y-m-d H:i:s"),"login_count"=>$login_count->login_count+1),array("id="=>$candidate['id']));
				$this->redirect(array("candidate"=>"index"));
			}else{
				$check=$user->checkSession($sessionId,$_SERVER["REMOTE_ADDR"]);
				$check?$this->logout():$this->redirect(array("candidate"=>"index"));
			}
		}else{
			$this->redirect(array("candidate"=>"loginpage"),array("can_login_err"=>"Username and Password wrong !"));
		}
	}
	public function logout(){
		$candidate = $this->loadModel("Candidate");
		$candidate->update(array("logout_date"=>date("Y-m-d H:i:s")),array("id="=>$this->can_session['id']));
		//Session::destroy();
		Session::kill("candidate");
		$this->redirect(array("candidate"=>"loginpage"));
	}
	public function reset(){
		$candidate = $this->loadModel("Candidate");
		$user = $this->loadModel("User");
		
		//check is the old password is existed or not ?
		$result = $user->checkRecord("Candidates",array("password"),array("username="=>$this->can_session["user"],"password="=>md5($this->get("oldpwd"))));
		$version = $user->getRecords(array("version"),array("id="=>$this->can_session["id"])) + 1;
		if($result){
			if($this->get("newpwd")==$this->get("confirmpwd")){
				$candidate->update(array("password"=>md5($this->get("newpwd")),"version"=>$version,"modified"=>date("Y-m-d H:i:s")),array("id="=>$this->can_session["id"]));
				if($this->get("ajax")==1){
					echo 1;
				}else{
					$this->redirect(array("candidate"=>"loginpage"));
				}
			}else{
				$this->set(array("pwdmissmatch"=>"Password is missmatch !"));
				$this->redirect(array("candidate"=>"resetpage"));
			}
		}else{
			if($this->get("ajax")==1){
				echo 0;
			}else{
				$this->set(array("incorect"=>"Incorrect old password"));
				$this->redirect(array("employer"=>"resetpage"));
			}
		}
	}
	public function resetFromMail(){
		$candidate = $this->loadModel("Candidate");
		$user = $this->loadModel("User");
		$recordCan = $this->model->findAsObject(array("id="=>$this->get("canId")));
		//check is the old password is existed or not ?
		$result = $user->checkRecord("Candidates",array("password"),array("username="=>$recordCan->username,"password="=>$recordCan->password,"email="=>$recordCan->email));
		$version = $user->getRecords(array("version"),array("id="=>$recordCan->id)) + 1;
		if($result){
			if($this->get("newpwd")==$this->get("confirmpwd")){
				$candidate->update(array("password"=>md5($this->get("newpwd")),"version"=>$version,"modified"=>date("Y-m-d H:i:s")),array("id="=>$recordCan->id));
				if($this->get("ajax")==1){
					echo 1;
				}else{
					$this->redirect(array("candidate"=>"loginpage"));
				}
			}else{
				$this->set(array("sms"=>"Password is missmatch !"));
				$this->redirect(array("candidate"=>"resetpage"),array("canId"=>$recordCan->id));
			}
		}else{
			if($this->get("ajax")==1){
				echo 0;
			}else{
				$this->set(array("sms"=>"Incorrect old password"));
				$this->redirect(array("candidate"=>"resetpage"),array("canId"=>$recordCan->id));
			}
		}
	}
	public function checkMail(){
		$candidate = $this->loadModel("Candidate");
		$checkmail = $candidate->checkCanEmail($this->get("email"));
		if($checkmail){
			echo "ok";
		}else{ echo "no";}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
	public function checkMailForgetPasswod(){
		$candidate = $this->loadModel("Candidate");
		$checkmail = $candidate->checkCanEmail($this->get("email"));
		if($checkmail==$this->get("email")){
			echo "ok";
		}elseif($checkmail!=$this->get("email")){ 
			echo "no";
		}elseif($checkmai==""){
			echo 0;
		}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
	public function registerAjax(){
		//echo md5($this->get("password"));exit();
		$result = array("error"=>"1","message"=>"Failed to login.");
		$candidate = $this->loadModel("Candidate");
		if($this->get("password")==$this->get("confirmpwd")){
			$recordCan = $candidate->save(array(
				"firstname"=>$this->get("firstname"),
				"lastname"=>$this->get("lastname"),
				"username"=>$this->get("username"),
				"password"=>md5($this->get("password")),
				"nickname"=>$this->get("nickname"),
				"email"=>$this->get("email"),
				//"signupdate"=>date("Y-m-d H:i:s"),
				"created"=>date("Y-m-d H:i:s") ,
				"ip"=>$_SERVER['REMOTE_ADDR'],
				"version"=>1));
			//
			//Send mail to surper admin and Candidate after candidate register already
			$arrMail = array($recordCan->email,"phonpisey23@gmail.com");
			$strEmp = "Welcome to HRCambodia!<br/>";
			$strSuperAdmin = "Here is the one who just registered with our company!<br/>";
			$strSuperAdmin .="Name : " .$recordCan->firstname ." ". $recordCan->lastname ."<br/>";
			//$strSuperAdmin .="Name of Company : " .$recordCan->company_name ."<br/>";
			$strSuperAdmin .="Email : " .$recordCan->email ."<br/>";
			$arrStr = array($strEmp,$strSuperAdmin);
			$arrSub = array("HRCambodia Alert Information","HRCambodia Alert Information");
			ob_start();
			//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
			Import::util('class.phpmailer');
			//the true param means it will throw exceptions on errors, which we need to catch
			$mail = new PHPMailer(true);
			//telling the class to use SMTP
			$mail->IsSMTP();
			try {
				// SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
				$mail->SMTPDebug = 1;
				// enable SMTP authentication
				$mail->SMTPAuth = true;
				// sets the SMTP server
				$mail->Host = "mail.atmos-techno.com";
				// set the SMTP port for the MY OWN DOMAIN server
				$mail->Port = 25;
				// SMTP account username
				$mail->Username = "demo@atmos-techno.com";
				// SMTP account password
				$mail->Password = "demo*123456";
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				for($i=0;$i<count($arrMail);$i++){
					// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
					$mail->AddAddress($arrMail[$i], 'HRCambodia');
					//$mail->AddAddress('phonpisey23@gmail.com','');
					$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
					$mail->Subject = "HRCambodia Alert " . $arrSub[$i];
					// optional - MsgHTML will create an alternate automatically
					$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
					$mail->MsgHTML($arrStr[$i]."<br/>");
					$mail->Send();
					$mail->ClearAddresses();
					$mail->ClearAttachments();
				}
			} catch (phpmailerException $e) {
				//Pretty error messages from PHPMailer
				echo $e->errorMessage();
			} catch (Exception $e) {
				//Boring error messages from anything else!
				echo $e->getMessage();
			}
			Session::set("candidate_id",$recordCan->id);
			Session::set("candidate_name",$recordCan->username);
			//$result["error"]=0;
			//$result["message"]="Successfully login !!!";
			$this->refresh(array("page"=>"index"),array(),3);
			echo "Register successfully,We refresh page in 3 seconds!";
			
		}
		//echo "(".json_encode($result).")";
	}
	public function save(){
		$candidate = $this->loadModel("Candidate");
		// Check email whether exist or not
		/*
		if(is_object($candidate -> findAsObject(array("email="=>$this->get("email"))))){
					$this->refresh(array("candidate"=>"loginpage"),3);
					echo "Your email is already exist. you will be redirected to the login's page within 3 seconds" ;
				}*/
		
		// Check password whether match or not
		$code = $this->get("captcha");
		$captcha = Session::get("vercode");
		if($code ==$captcha){
			$record = $candidate->save(array(
					"ip"=>$_SERVER["REMOTE_ADDR"],
					"firstname"=>$this->get("firstname"),
					"lastname"=>$this->get("lastname"),
					"username"=>$this->get("username"),
					"nickname"=>$this->get("nickname"),
					"Validated"=>"N",
					"password"=>md5($this->get("password")),
					"email"=>$this->get("email"),
					"signup_date"=>date("Y-m-d"),
					"created"=>date("Y-m-d H:i:s"),
					"admin_view"=> 0,
					"modified"=>date("Y-m-d H:i:s"),
					"version"=>1));
			// send mail to client to let she/her verify her/his account
			// this section is missing
			$this->refresh(array("candidate"=>"loginpage"),array(),3);
			echo "You have registered successlly. you will be redirected to login's page within 3 seconds.";
		}else{
			$this->redirect(array("candidate"=>"registerpage"),array("err"=>"Incorrect verification code, Try again"),3);
		}
	}

	public function update(){
		$candidate = $this->loadModel("Candidate") ;
		$version = $candidate->findAsObject(array("id="=>$this->can_session["id"]));
		$candidate->update(
			array(
				"ip"=>$_SERVER["REMOTE_ADDR"],
				"firstname"=>$this->get("firstname"),
				"lastname"=>$this->get("lastname"),
				"email"=>$this->get("email"),
				"nickname"=>$this->get("nickname"),
				"version"=> $version->version ,
				"modified"=>date("Y-m-d H:i:s"),
				"modified_by"=>$this->can_session["id"]
			),
			array("id="=>$this->can_session["id"])
		);
		if($this->get("ajax")==NULL)$this->redirect(array("candidate"=>"index"));
		else echo 1;
	}

	public function remove(){
		$candidate = $this->loadModel("User") ;
		$candidate->delete(array("id="=>$this->can_session["id"]));
	}
	// UPLOAD FUNCTION FOR ONE OR MULTIPLE PHOTO
	public function upload(){
		Import::util("FileUpload");
		$user = Session::get("candidate_name");
		$folder = "data/cv/".$user ;
		if(!Basic::fileExist($folder))Basic::createFolder($folder);
		$gallery = $this->loadModel("Gallery");
		$infos=FileUpload::checkFileUpload($folder);
		$helper = true;
		$ids=array();
		foreach($infos as $info ){
			if($info["error"]["number"]==0){
				if(($record=$gallery->savephoto(array("uid"=>$this->can_session["id"],"gname"=>Session::get("candidate_name"),"name"=>$info["name"],"location"=>"","type"=>$info["type"],"size"=>$info["size"],"d_w"=>$info["dimension"]["width"],"d_h"=>$info["dimension"]["height"],"created"=>date("Y-m-d H:s:i"),"modified"=>date("Y-m-d H:s:i"))))!==false){
					$gallery->update(array("location"=>$folder."/".$record->id.".".$info["ext"]),array("id = "=>$record->id));
					$ids[]=$record->id;
					FileUpload::uploadFile($info["control"],$record->id.".".$info["ext"],5,$folder);
				}else{
					Basic::eco("<br/>There is an unexpected error occured during upload file.<br/>");
					Basic::pr($info);
					$help=false;
				}
			}
			else{
				// check error
			}
		}
		return !empty($ids)?$ids:false;
	}
/*  
	 * @Developer: vitou
	 * @Create Modify: 20-May-2014
	 * @Return check usernam
	 * */
	public function checkUserNameCan(){
		$candidate = $this->loadModel("Candidate") ; 
		$checkusername = $candidate->getUserNameCan($this->get("username"));
		if($checkusername==trim($this->get("username"))){
			echo "ok";
		}elseif($checkusername!=trim($this->get("username"))){ 
			echo "no";
		}elseif($checkusername==""){
			echo 0;
		}
		//$this->redirect(array("candidate"=>"registerpage"));
	}
	public function showItemsDropdownSearch(){
			
		$categories = $this->loadModel("Categorie");
		$time=$categories->getCategories(20);
		$this->set(array("jobcategory"=>$categories->getCategories(23)));
		$this->set(array("location"=>$categories->getCategories(1)));
		$this->set(array("jobtime"=>$categories->getCategories(20)));
		$this->set(array("country"=>$categories->getCategories(244)));
		$this->set(array("qualification"=>$categories->getCategories(143)));
	}
	public function getCatogorys(){
		$category = $this->loadModel("Categorie");
		$this->set(array("location"=>$category->getCategories(1)));
		$this->set(array("jobtype"=>$category->getCategories(20)));
		$this->set(array("jobmode"=>$category->getCategories(133)));
		$this->set(array("joblevel"=>$category->getCategories(137)));
		$this->set(array("level"=>$category->getCategories(151)));
		$this->set(array("language"=>$category->getCategories(156)));
		$this->set(array("gender"=>$category->getCategories(173)));
		$this->set(array("industry"=>$category->getCategories(179)));
		$this->set(array("companytype"=>$category->getCategories(227)));
		$this->set(array("jobcategory"=>$category->getCategories(23)));
		$this->set(array("qualification"=>$category->getCategories(143)));
		$this->set(array("days"=>$category->getCategories(287)));
		$this->set(array("months"=>$category->getCategories(255)));
	}
	public function getCatogorysAssoc(){
		$category = $this->loadModel("Categorie");
		$this->set(array("locationKey"=>$category->getCategoriesAsASSOC(1)));
		$this->set(array("jobtypeKey"=>$category->getCategoriesAsASSOC(20)));
		$this->set(array("jobmodeKey"=>$category->getCategoriesAsASSOC(133)));
		$this->set(array("joblevelKey"=>$category->getCategoriesAsASSOC(137)));
		$this->set(array("levelKey"=>$category->getCategoriesAsASSOC(151)));
		$this->set(array("languageKey"=>$category->getCategoriesAsASSOC(156)));
		$this->set(array("genderKey"=>$category->getCategoriesAsASSOC(173)));
		$this->set(array("industryKey"=>$category->getCategoriesAsASSOC(179)));
		$this->set(array("companytypeKey"=>$category->getCategoriesAsASSOC(227)));
		$this->set(array("jobcategoryKey"=>$category->getCategoriesAsASSOC(23)));
		$this->set(array("qualificationKey"=>$category->getCategoriesAsASSOC(143)));
		$this->set(array("daysKey"=>$category->getCategoriesAsASSOC(287)));
		$this->set(array("monthsKey"=>$category->getCategoriesAsASSOC(255)));
	}
	public function Subscript(){
		$membership = $this->loadModel("Membership");
		$candidate = $this->loadModel("Candidate");
		$category = $this->loadModel("Categorie");
		$employer = $this->loadModel("Employer");
		$job = $this->loadModel("Job");
		$post = $this->loadModel("Post");
		$id = $this->get("cat_id");
		$type = $this->get("type");
		if($type=="catid"){
			$valmembership = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate","cat_id ="=>$id));
			$membershipId = isset($valmembership->user_id)?$valmembership->user_id:NULL;
			$membershipCat = isset($valmembership->cat_id)?$valmembership->cat_id:NULL;
			$getOldField = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate"));
			$getOldId = isset($getOldField->user_id)?$getOldField->user_id:NULL;
			$getOldCat = isset($getOldField->cat_id)?$getOldField->cat_id:NULL;
		}else if($type=="locid"){
			$valmembership = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate","loc_id ="=>$id));
			$membershipId = isset($valmembership->user_id)?$valmembership->user_id:NULL;
			$membershipCat = isset($valmembership->loc_id)?$valmembership->loc_id:NULL;
			$getOldField = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate"));
			$getOldId = isset($getOldField->user_id)?$getOldField->user_id:NULL;
			$getOldCat = isset($getOldField->loc_id)?$getOldField->loc_id:NULL;
		}else if($type=="timeid"){
			$valmembership = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate","time_id ="=>$id));
			$membershipId = isset($valmembership->user_id)?$valmembership->user_id:NULL;
			$membershipCat = isset($valmembership->time_id)?$valmembership->time_id:NULL;
			$getOldField = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate"));
			$getOldId = isset($getOldField->user_id)?$getOldField->user_id:NULL;
			$getOldCat = isset($getOldField->time_id)?$getOldField->time_id:NULL;
		}
		if($membershipId == NULL && $membershipCat == NULL){
			/* compare user id  */
			if($getOldId == $this->can_session["id"] && $membershipCat===$id){
					if($this->get("type") == "catid"){
						$getDataSave = $membership->update(array("cat_id"=>$id,"version"=>$version + 1),array("user_id = "=>$this->can_session["id"]));
					}else if($this->get("type") == "locid"){
						$getDataSave = $membership->update(array("loc_id"=>$id,"version"=>$version + 1),array("user_id = "=>$this->can_session["id"]));
					}else{
						$getDataSave = $membership->update(array("time_id"=>$id,"version"=>$version + 1),array("user_id = "=>$this->can_session["id"]));
					}
			}else{
				if($this->get("type") == "catid"){
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"cat_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}else if($this->get("type") == "locid"){
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"loc_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}else{
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"time_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}

			}
		}else{
			if($membershipId == $this->can_session["id"] && $membershipCat == $id){
				//Sth happen
				$getDataSave = "";
				exit();
			}else{
				if($this->get("type") == "catid"){
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"cat_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}else if($this->get("type") == "locid"){
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"loc_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}else{
					$getDataSave = $membership->save(array("user_id"=>$this->can_session["id"],"time_id"=>$id,"sub_type"=>"Candidate","created"=>date("Y-m-d H:i:s"),"version"=>"1"));
				}

			}
		}
		//get record that save successful
		if($type=="catid"){
			$getMembership = $membership->findAsObject(array("user_id = "=>$getDataSave->user_id,"sub_type ="=>"Candidate","cat_id = "=>$getDataSave->cat_id));
			$recordCan = $candidate->findAsObject(array("id = "=>$getMembership->user_id));
			$getJobByCats = $job->getMultiRecord($getMembership->cat_id);
		}else if($type=="locid"){
			$getMembership = $membership->findAsObject(array("user_id = "=>$getDataSave->user_id,"sub_type ="=>"Candidate","loc_id = "=>$getDataSave->loc_id));
			$recordCan = $candidate->findAsObject(array("id = "=>$getMembership->user_id));
			$getJobByCats = $job->getMultiRecord($getMembership->loc_id);
		}else if($type=="timeid"){
			$getMembership = $membership->findAsObject(array("user_id = "=>$getDataSave->user_id,"sub_type ="=>"Candidate","time_id = "=>$getDataSave->time_id));
			$recordCan = $candidate->findAsObject(array("id = "=>$getMembership->user_id));
			$getJobByCats = $job->getMultiRecord($getMembership->time_id);
		}
		
		
		$recordEmp = array();
		foreach($getJobByCats as $getJobByCat){
			$recordEmp[] = $employer->findAsObject(array("id="=>$getJobByCat->user_id));
		}
		exit();
		//Roth Testing
		$getAllCategories = $category->getAllCategories();
		$strEmp ="Dear Sir/Madam <br/><br/>";
		$strEmp .= "Here is the one who was just subscribed with your job category!<br/>";
		$strEmp .="Name : " . $recordCan->firstname ." ". $recordCan->lastname ."<br/>";
		$strEmp .="Email : " . $recordCan->email ."<br/>";
		$strCan ="Dear " . $recordCan->firstname ." ". $recordCan->lastname ."<br/><br/>";
		$strCan .= "You have just subscribed to job's field(s) as follow: <br/>";
		foreach ($getAllCategories as $getCat){
			if($getCat["id"] == $id){
				$cat = $getCat["name"];
			}
		}
		$strCan .="Category : " .$cat ."<br/>";
		$strCan .="You will receive new email of new job with this/these category/ies.<br/>";
		$strCan .= "<br/><br/>Thanks for your subscription.<br/>";
		//send mail to employer after updated status
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			//
			//send to candidate
			$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
			// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
			$mail->AddAddress($recordCan->email, 'HRCambodia');
			//$mail->AddAddress('phonpisey23@gmail.com','');
			$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
			$mail->Subject = "HRCambodai .com Alert Jobs Information";
			// optional - MsgHTML will create an alternate automatically
			$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
			$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strCan . "<br/>");
			$mail->Send();
			$mail->ClearAddresses();
			$mail->ClearAttachments();
			//Send mail to Employer	
			for($i=0; $i< count($recordEmp); $i++){
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($recordEmp[$i]->email, 'HRCambodia');
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "HRCambodai .com Alert Information";
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strEmp. "<br/>");
				$mail->Send();
				$mail->ClearAddresses();
				$mail->ClearAttachments();
			}
		}catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			//echo $e->errorMessage();
		}catch (Exception $e) {
			//Boring error messages from anything else!
			//echo $e->getMessage();
		}
		
		
		$membership = $this->loadModel("Membership");
		$category = $this->loadModel("Categorie");
		$candidateMemberships = $membership->getCandidateMemberships($this->can_session["id"]);
		$categories = $category->getCategoriesAsArray(); 
		$this->set("candidateMemberships",$candidateMemberships);
		$this->set("categories",$categories);
		$this->set("main_content","main_content");
		$this->set(array("mnu"=>"sub"));
		$this->render("viewsub");
	}

	public function Unsubcription(){
		$membership = $this->loadModel("Membership");
		$candidate = $this->loadModel("Candidate");
		$employer = $this->loadModel("Employer");
		$category = $this->loadModel("Categorie");
		$job = $this->loadModel("Job");
		$post = $this->loadModel("Post");
		$id = $this->get("cat_id");
		$valmembership = $membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate","cat_id ="=>$id));
		$recordCan = $candidate->findAsObject(array("id = "=>$valmembership->user_id));
		$getJobByCats = $job->getMultiRecord($valmembership->cat_id);
		foreach($getJobByCats as $getJobByCat){
			$recordEmp[] = $employer->findAsObject(array("id = "=>$getJobByCat->user_id));
		}
		/*
		$getAllCategories = $category->getAllCategories();
		$strEmp ="Dear Sir/Madam <br/><br/>";
		$strEmp .= "Here is the one who just was unsubscribed with your job category!<br/>";
		$strEmp .="Name : " . $recordCan->firstname ." ". $recordCan->lastname ."<br/>";
		$strEmp .="Email : " . $recordCan->email ."<br/>";
		$strCan ="Dear " . $recordCan->firstname ." ". $recordCan->lastname ."<br/><br/>";
		$strCan .= "This is the job that you just was unsubscribed with!<br/>";
		foreach ($getAllCategories as $getCat){
			if($getCat["id"] == $id){
				$cat = $getCat["name"];
			}
		}
		$strCan .="Category : " .$cat ."<br/>";
		//send mail to employer after updated status
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			//
			//send to candidate
			$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
			// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
			$mail->AddAddress($recordCan->email, 'HRCambodia');
			//$mail->AddAddress('phonpisey23@gmail.com','');
			$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
			$mail->Subject = "HRCambodai .com Alert Information";
			// optional - MsgHTML will create an alternate automatically
			$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
			$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strCan . "<br/>");
			$mail->Send();
			$mail->ClearAddresses();
			$mail->ClearAttachments();
			//send to employer
			for($i=0;$i<count($recordEmp);$i++){
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($recordEmp[$i]->email, 'HRCambodia');
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "HRCambodai .com Alert Information";
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strEmp. "<br/>");
				$mail->Send();
				$mail->ClearAddresses();
				$mail->ClearAttachments();
			}
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			//echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			//echo $e->getMessage();
		}
		*/
		
		//Update or delete
		if($valmembership->posting_point != "0"){
			$version = $membership->findObject(array("user_id = "=>$this->emp_session["id"]));
			$getDataSave = $membership->update(array("cat_id"=>NULL,"version"=>$version + 1),array("user_id = "=>$this->can_session["id"]));			
		}else if(strtotime($valmembership->subscription_expire) != "0"){
			$version = $membership->findObject(array("user_id = "=>$this->emp_session["id"]));
			$getDataSave = $membership->update(array("cat_id"=>NULL,"version"=>$version + 1),array("user_id = "=>$this->can_session["id"]));
		}else{
			$getDataSave = $membership->delete(array("cat_id="=>$valmembership->cat_id,"user_id ="=>$valmembership->user_id));
		}
		//do by pisey
		$membership = $this->loadModel("Membership");
		$category = $this->loadModel("Categorie"); 
		$candidateMemberships = $membership->getCandidateMemberships($this->can_session["id"]);
		$categories = $category->getCategoriesAsArray(); 
		$this->set("candidateMemberships",$candidateMemberships);
		$this->set("categories",$categories); 
		$this->set("main_content","main_content"); 
		$this->render("viewsub");
	}
	/* test */
public function UnsubcriptionMain(){
	
		$membership = $this->loadModel("Membership");
		$candidate = $this->loadModel("Candidate");
		$employer = $this->loadModel("Employer");
		$category = $this->loadModel("Categorie");
		$job = $this->loadModel("Job");
		$post = $this->loadModel("Post");
		$id = $this->get("id");
		$valmembership = @$membership->findAsObject(array("user_id = "=>$this->can_session["id"],"sub_type="=>"Candidate","id ="=>$this->get("id")));
		$getJob = @$job->getObject(array("job_category = "=>$valmembership->cat_id));
		$recordCan = @$candidate->findAsObject(array("id = "=>$valmembership->user_id));
		$getJobByCats = @$job->getMultiRecord($valmembership->cat_id);
		$recordEmp = array();
		foreach($getJobByCats as $getJobByCat){
			$recordEmp[] = $employer->findAsObject(array("id = "=>$getJobByCat->user_id));
		}
		/*
		$getAllCategories = $category->getAllCategories();
		$strEmp ="Dear Sir/Madam <br/><br/>";
		$strEmp .="Here is the one who just was unsubscribed with your job category!<br/>";
		$strEmp .="Name : " . $recordCan->firstname ." ". $recordCan->lastname ."<br/>";
		$strEmp .="Email : " . $recordCan->email ."<br/>";
		$strCan ="Dear " . $recordCan->firstname ." ". $recordCan->lastname ."<br/><br/>";
		$strCan .= "This is the job category that you just was unsubscribed with!<br/>";
		foreach ($getAllCategories as $getCat){
			if($getCat["id"] == $getJob->job_category){
				$cat = $getCat["name"];
			}
		}
		$strCan .="Category : " .$cat ."<br/>";
		//send mail to employer after updated status
		ob_start();
		//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
		Import::util('class.phpmailer');
		//the true param means it will throw exceptions on errors, which we need to catch
		$mail = new PHPMailer(true);
		//telling the class to use SMTP
		$mail->IsSMTP();
		try {
			// SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
			$mail->SMTPDebug = 1;
			// enable SMTP authentication
			$mail->SMTPAuth = true;
			// sets the SMTP server
			$mail->Host = "mail.atmos-techno.com";
			// set the SMTP port for the MY OWN DOMAIN server
			$mail->Port = 26;
			// SMTP account username
			$mail->Username = "demo@atmos-techno.com";
			// SMTP account password
			$mail->Password = "demo*123456";
			//send to candidate
			$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
			// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
			$mail->AddAddress($recordCan->email, 'HRCambodia');
			//$mail->AddAddress('phonpisey23@gmail.com','');
			$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
			$mail->Subject = "HRCambodai .com Alert Information";
			// optional - MsgHTML will create an alternate automatically
			$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
			$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strCan . "<br/>");
			$mail->Send();
			$mail->ClearAddresses();
			$mail->ClearAttachments();
			//send to employer
			for($i=0;$i<count($recordEmp);$i++){
				$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
				// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
				$mail->AddAddress($recordEmp[$i]->email, 'HRCambodia');
				//$mail->AddAddress('phonpisey23@gmail.com','');
				$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
				$mail->Subject = "HRCambodai .com Alert Unsubscription Information";
				// optional - MsgHTML will create an alternate automatically
				$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
				$mail->MsgHTML("<h3>HRCambodia Alert Information</h3>" . $strEmp. "<br/>");
				$mail->Send();
				$mail->ClearAddresses();
				$mail->ClearAttachments();
			}
		} catch (phpmailerException $e) {
			//Pretty error messages from PHPMailer
			//echo $e->errorMessage();
		} catch (Exception $e) {
			//Boring error messages from anything else!
			//echo $e->getMessage();
		}
		//
		 * */
		//Update or delete
		if(@$valmembership->posting_point != "0"){
			$version = $membership->findObject(array("user_id = "=>$this->emp_session["id"]));
			$getDataSave = $membership->update(array("cat_id"=>NULL,"version"=>$version + 1),array("cat_id = "=>$id));
			$getDataSave = $membership->update(array("loc_id"=>NULL,"version"=>$version + 1),array("loc_id = "=>$id));
			$getDataSave = $membership->update(array("time_id"=>NULL,"version"=>$version + 1),array("time_id = "=>$id));
			echo 1;
		}else if(strtotime($valmembership->subscription_expire) != "0"){
			$version = $membership->findObject(array("user_id = "=>$this->emp_session["id"]));
			$getDataSave = $membership->update(array("cat_id"=>NULL,"version"=>$version + 1),array("cat_id = "=>$id));
			$getDataSave = $membership->update(array("loc_id"=>NULL,"version"=>$version + 1),array("loc_id = "=>$id));
			$getDataSave = $membership->update(array("time_id"=>NULL,"version"=>$version + 1),array("time_id = "=>$id));
			echo 1;
		}else{
			$getDataSave = $membership->delete(array("cat_id="=>$valmembership->cat_id));
			$getDataSave = $membership->delete(array("loc_id="=>$valmembership->loc_id));
			$getDataSave = $membership->delete(array("time_id="=>$valmembership->time_id));
			echo 1;
		}
	}
	
	
	public function join(){
		$this->render("new_register");
	}
	public function forgot(){
		$this->render("forgot_pswd");
	}
	public function viewSub(){
		$membership = $this->loadModel("Membership");
		$category = $this->loadModel("Categorie");
		$memberJob = $this->loadModel("Membership");
		$candidateMemberships = $membership->getCandidateMemberships($this->can_session["id"]);
		$categories = $category->getCategoriesAsArray();
		$this->set(array("jobcategory"=>$category->getCategories(23)));
		$this->set(array("jobloc"=>$category->getCategories(1)));
		$this->set(array("jobtime"=>$category->getCategories(20)));
		$this->set(array("categories"=>$categories));
		$this->set(array("memberJob1"=>$memberJob->getPage($this->can_session["id"],1,20,array("created"),"DESC")));
		$this->set(array("memberJob2"=>$memberJob->getPage1($this->can_session["id"],1,20,array("created"),"DESC")));
		$this->set(array("memberJob3"=>$memberJob->getPage2($this->can_session["id"],1,20,array("created"),"DESC")));
		$this->set("candidateMemberships",$candidateMemberships);
		$this->set("cates",$category->getCategories(23));
		$this->set("locs",$category->getCategories(1));
		$this->set("times",$category->getCategories(20));
		$resume = $this->loadModel("Resume");
		$row = $resume->getResumeWithUser($this->can_session["id"]) ;
		$profilePhoto = !empty($row )&&is_object($row->rem_uploadImg)?ROOT.$row->rem_uploadImg->location:"";
		$this->set(array("profile_picture"=>$profilePhoto));
		$this->set(array("mnu"=>"sub"));
		$this->set(array("layout"=>"sub"));
		$this->render("admin");
	}
	public function sendMail(){
		$candidate = $this->loadModel("Candidate");
		$txtMail = $this->get("txtForgot");
		$findObject = $candidate->findAsObject(array("email = "=>$txtMail));
		$date = date("Y-m-d H:i:s");
		$date = strtotime($date);
		$date = strtotime("+1 day" , $date);
		$linkExp = date('Y-m-d H:i:s', $date);
		@$this->model->update(array("link_expire"=>$linkExp),array("id="=>$findObject->id));
		if($findObject){
			if($txtMail == $findObject->email){
				$str = "<b>HRCambodia .com Your New Password!</b><br/>";
				$str = "Please, click on this link to reset your password <a href='".SERVER.ROOT."index.php/candidate/resetpage/canId:$findObject->id'>click</a>";
				ob_start();
				//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
				Import::util('class.phpmailer');
				//the true param means it will throw exceptions on errors, which we need to catch
				$mail = new PHPMailer(true);
				//telling the class to use SMTP
				$mail->IsSMTP();
				try {
					// SMTP server
					$mail->Host = "mail.atmos-techno.com";
					// enables SMTP debug information (for testing),  show debug : SMTPDebug  = 2,  Hide debug : SMTPDebug  = 1
					$mail->SMTPDebug = 1;
					// enable SMTP authentication
					$mail->SMTPAuth = true;
					// sets the SMTP server
					$mail->Host = "mail.atmos-techno.com";
					// set the SMTP port for the MY OWN DOMAIN server
					$mail->Port = 26;
					// SMTP account username
					$mail->Username = "demo@atmos-techno.com";
					// SMTP account password
					$mail->Password = "demo*123456";
					//$mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
					//$mail->AddAddress('physopheak10@gmail.com', '');
					//$mail->AddAddress('phonpisey23@gmail.com','');
					$email_address = filter_input(INPUT_GET, $findObject->email, FILTER_VALIDATE_EMAIL);
					if (!$email_address) {
						$mail->SetFrom('demo@atmos-techno.com', 'HRCambodia');
						// $mail->AddAddress('info@atmos-techno.com', 'Atmosphere Technology Co.,Ltd');
						$mail->AddAddress($findObject->email, ' ');
						//$mail->AddAddress('phonpisey23@gmail.com','');
						$mail->AddReplyTo('demo@atmos-techno.com', 'sales@hrcambodia.com');
						$mail->Subject = "HRCambodia .com Alert New Password";
						// optional - MsgHTML will create an alternate automatically
						$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
						$mail->MsgHTML("<h3>Link Password Information</h3>" . $str . "<br/>");
						$mail->Send();
						$this->refresh(array("page"=>"index"),array(),4);
						echo "Reset password successfully,Please go to your email to reset your password!";
					} else {
						//echo 'Email is invalid...';
						break;
					}
				} catch (phpmailerException $e) {
					//Pretty error messages from PHPMailer
					echo $e->errorMessage();
				} catch (Exception $e) {
					//Boring error messages from anything else!
					echo $e->getMessage();
				}
			}else{
				$this->set(array("message"=>"Email not found on the system. Try again"));
				$this->render("forgot_pswd");
			}
				
		}else{
			$this->set(array("message"=>"Email not found on the system. Try again"));
			$this->render("forgot_pswd");
		}
	}
	public function pview(){
			$candidate = $this->loadModel("Candidate");
			$record = $candidate->getAlljob(array("id = "=>$this->get("id")));
			$this->set(array("record"=>$record));
			$this->render("pview");
		
	}
	public function Captcha(){
		//$text = $ranStr = md5(microtime());
		//$text = substr($ranStr, 0, 6);
		$text = $ranStr = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
		Session::set("vercode",$text);
		$height = 30;
		$width = 70;
		
		$image_p = imagecreate($width, $height);
		$black = imagecolorallocate($image_p, 5, 5, 5);
		$white = imagecolorallocate($image_p, 255, 255, 255);
		$font_size = 15;
		
		imagestring($image_p, $font_size, 5, 5, $text, $white);
		imagejpeg($image_p, null, 80);
	}
	/** Mr. Phireak
	 * get record information of candidate to print report 
	 * 
	 */
	public function record(){
		$resume = $this->loadModel("Resume");
		$this->set(array("mnu"=>"record","layout"=>"record"));
		//scoring of candidate
		$point = $this->loadModel("Point");
		$this->set(array("point_record"=>$point->findAsObject(array("can_id="=>$this->can_session["id"]))));
		$this->set(array("row"=>$resume->getResumeWithUser($this->can_session["id"])));
		$this->render("admin");
	}
	public function help(){
		$this->set(array("layout"=>"help"));
		$this->render("admin");
	}
}
